/**
 * 搜索并选择历史客户
 */

var clientSelector;

//页面载入初始化
$( "body" ).ready( function( e )
{
	clientSelector = new ClientSelector();
	clientSelector.init();
} );

//窗口大小改变
$( window ).resize( function( e )
{
	if( clientSelector.visibled() )
	{
		clientSelector.relocate();
	}
} );

function ClientSelector()
{
	var html = "<div id='__DIV_ITEMADDER_MASK' style='display:block;position:absolute;background-color:#000;filter:alpha(opacity=20);opacity:0.2;'></div>"
			+ "<div id='__DIV_ITEMADDER' style='position:absolute;'>"
			+ "<dt><span id='title'>历史客户资源搜索</span><a id='btn_cancel'>[ 取消 ]</a> <a id='btn_enter'>[ 确定 ]</a></dt>"
			+ "<div id='body'></div>" + "</div>";

	var $mask;
	var $box;
	var $body;
	var callback;

	var _moveable = false;

	this.init = function()
	{
		$( "body" ).append( html );
		$box = $( "#__DIV_ITEMADDER" );
		$mask = $( "#__DIV_ITEMADDER_MASK" );
		$body = $box.find( "#body" );

		$box.find( "dt" ).bind( { mousedown: function( e )
		{
			_moveable = true;

			// 鼠标相对于当前窗口的位置
			var offsetX = e.pageX - $box.x();
			var offsetY = e.pageY - $box.y();

			$( "body" ).bind( "mousemove", { ox: offsetX, oy: offsetY }, function( e )
			{
				if( _moveable )
				{
					$box.move( e.pageX - e.data.ox, e.pageY - e.data.oy );
				}
			} );
		}, mouseup: function( e )
		{
			_moveable = false;
			$( "body" ).unbind( "mousemove" );
		} } );

		$box.find( "#btn_cancel" ).click( { cur: this }, function( e )
		{
			e.stopPropagation();
			var pcur = e.data.cur;
			pcur.close();
		} );
		$box.find( "#btn_enter" ).click( { cur: this }, function( e )
		{
			e.stopPropagation();
			var pcur = e.data.cur;

			if( typeof ( callback ) == "function" )
				callback();

			pcur.close();
		} );

		$box.hide();
		$mask.hide();
	};

	// 是否显示
	this.visibled = function()
	{
		return $box.visible();
	};

	// 显示单条信息
	this.open = function( )
	{
		this.relocate();
		$box.fadeIn( 150 );
		$mask.fadeIn( 150 );
	};

	this.relocate = function()
	{
		var bw = $( "body" ).width();
		var bh = $( "body" ).height();
		var w = $box.width();
		var h = $box.height();

		$mask.width( bw );
		$mask.height( bh );
		$mask.move( 0, 0 );
		$box.move( ( bw - w ) / 2, ( bh - h ) / 2 * 0.8 );
	};

	this.close = function()
	{
		$box.fadeOut( 150 );
		$mask.fadeOut( 150 );
	};

	this.setCallback = function( fn )
	{
		callback = fn;
	};
}
